﻿using Microsoft.EntityFrameworkCore;
using Net6Template.DB.Models;
using Net6Template.Entity;
using Net6Template.Entity.Request.Account;
using Net6Template.Tools;

namespace Net6Template.Services
{
    public class AccountService
    {
        private readonly IDbContextFactory<NcfContext> _contextFactory;
        private readonly ResponseMessage _res;
        public AccountService(IDbContextFactory<NcfContext> contextFactory,
            ResponseMessage res)
        {
            _contextFactory = contextFactory;
            _res = res;
        }

        public async Task<ResponseMessage> GetAccountsAsync()
        {
            using var _context = _contextFactory.CreateDbContext();

            var result = await _context.TAccounts
                .Where(account => account.IsDelete == 0).ToListAsync();

            _res.data = result;
            return _res;
        }

        public async Task<ResponseMessage> GetAccountsByPageAsync(int pageIndex, int pageSize)
        {
            using var _context = _contextFactory.CreateDbContext();

            var query = _context.TAccounts
                .Where(account => account.IsDelete == 0);

            var result = await query.GetPaged(pageIndex, pageSize).ToListAsync();

            _res.data = result;
            return _res;
        }

        public async Task<ResponseMessage> GetAccountAsync(int accountId)
        {
            using var _context = _contextFactory.CreateDbContext();

            var account = await _context.TAccounts.FirstAsync(p => p.AccountId == accountId && p.IsDelete == 0);

            _res.data = account;
            return _res;
        }

        public async Task<ResponseMessage> CreateAccountAsync(AccountRequest postData)
        {
            using var _context = _contextFactory.CreateDbContext();
            int changes = 0;
            if (postData.AccountId > 0)
            {
                var account = await _context.TAccounts.FirstAsync(p => p.AccountId == postData.AccountId);
                account.MobilePhone = postData.MobilePhone;
                _context.Update(account);

                changes = await _context.SaveChangesAsync();
            }
            else
            {
                TAccount account = new() { MobilePhone = postData.MobilePhone };
                _context.Add(account);

                changes = await _context.SaveChangesAsync();

            }
            _res.data = changes;
            return _res;
        }

        public async Task<ResponseMessage> DeleteAccountAsync(int accountId)
        {
            using var _context = _contextFactory.CreateDbContext();
            var account = await _context.TAccounts.FirstAsync(p => p.AccountId == accountId);
            account.IsDelete = 1;
            _context.Update(account);

            _res.data = await _context.SaveChangesAsync();
            return _res;
        }
    }
}
